# -*- coding: utf-8 -*-
"""
Created on Mon Jul  3 15:12:55 2023

@author: lenovo
"""

# -*- encoding: utf-8 -*-
'''
@File    :   calculate_area.py
@Time    :   2023/03/27 20:50:23
@Author  :   HMX
@Version :   1.0
@Contact :   kzdhb8023@163.com
'''


# here put the import lib
import numpy as np
from osgeo import gdal,osr
import time
import os
import glob
import shutil
from tqdm import tqdm # 运行计时

def projtif(intif,outtif,xres = 30,yres = 30):
    # 创建Albers等面积投影对象
    spatial_ref = osr.SpatialReference()
    spatial_ref.ImportFromProj4("+proj=aea +lat_1=25 +lat_2=47 +lat_0=0 +lon_0=105 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs")
    
    gdal.Warp(outtif , # 输出栅格路径
            intif,  # 输入栅格
            format='GTiff',  # 导出tif格式
            dstSRS = spatial_ref, # 投影
            xRes=xres, # 重采样后的x方向分辨率
            yRes=yres, # 重采样后的y方向分辨率
            resampleAlg=gdal.GRA_NearestNeighbour, #最临近重采样
            creationOptions=['COMPRESS=LZW']#lzw压缩栅格
            )
    return outtif


def tif2arr(tif):
    ds = gdal.Open(tif)
    arr = ds.ReadAsArray()
    return arr


if __name__ == '__main__':
    t1 = time.time()
    
    path=r'H:\company\公司项目\陕西\商洛\data'
    tiffdir=path+'\\masked\\'
    tiffile_all = glob.glob(tiffdir+'*.tif')
    
    outpath=path+'\\masked\\Alberts'
    if os.path.exists(outpath):
        shutil.rmtree(outpath)
        os.mkdir(outpath)
    else:
        os.mkdir(outpath)
    

    for tif_file in tqdm(tiffile_all):
        tif_file_folder,tif_file_name = os.path.split(tif_file)
        outtif = outpath + '\\' + \
            tif_file_name.replace('.tif','_Alberts.tif') # 输出文件
            
        projtif(tif_file,outtif,30,30)
    

    t2 = time.time()
    print('共计用时{:.2f}'.format(t2-t1))